package com.project.nimsen.web.pub;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.util.CollectionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.project.nimsen.dto.WxsendmsgDto;
import com.project.nimsen.entity.Site;
import com.project.nimsen.entity.Wxsendmsg;
import com.project.nimsen.service.IWxsendmsgService;
import com.project.nimsen.util.NimsenUtil;
import com.project.nimsen.util.WebUtil;
import com.project.nimsen.weixin.bean.BaseMsg;
import com.project.nimsen.weixin.bean.ImgTextSMsg;
import com.project.nimsen.weixin.bean.ImgTextSMsg.ImgTextItem;
import com.project.nimsen.weixin.bean.TextRMsg;
import com.project.nimsen.weixin.bean.TextSMsg;
import com.project.nimsen.weixin.common.WeiXinConstant;
import com.project.nimsen.weixin.utils.SignUtil;
import com.project.nimsen.weixin.utils.WXMessageUtils;
import com.project.jdbc.web.BaseMVCAction;
/**
 * 首页访问时的action类
 * */
@Controller
@RequestMapping(value ="/pub/wx")
public class WeiXinControl extends BaseMVCAction {
	@Resource
	WebUtil webUtil;
	@Resource
	IWxsendmsgService wxsendmsgService;
	@RequestMapping(value={"/pt/*"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
	public void get(HttpServletRequest request, HttpServletResponse response){
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		
		try {
			PrintWriter out = response.getWriter();
			if (SignUtil.checkSignature(webUtil.wx_token(request), signature, timestamp, nonce)) {
				out.write(echostr);
			}
			out.close();
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
	}
	@RequestMapping(value={"/pt/*"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
	public void post(HttpServletRequest request, HttpServletResponse response){
		try {
			String url = request.getServletPath();
			request.setCharacterEncoding("UTF-8");
			BaseMsg baseMsg = WXMessageUtils.xml2Msg(request);//把接收的信息类转换成类
			response.setCharacterEncoding("UTF-8");
			String xml =sendxml(baseMsg, request);
			response.getWriter().println(xml);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
	}
	/**
	 * 得到回复的内容信息
	 * */
	private String sendxml(BaseMsg rMsg, HttpServletRequest request)throws Exception{
		BaseMsg msgs = null;
		Site site = webUtil.currSite(request);
		if (rMsg instanceof TextRMsg) {
			TextRMsg txtMsg = (TextRMsg) rMsg;
			String keyword = txtMsg.getContent();
			Wxsendmsg msg = wxsendmsgService.findByKeyWord(keyword, site.getId());
			if(msg==null)
				msg = defaultmsg(site.getId());
			msgs = sendMsg(msg, rMsg);
		}
		msgs.setCreateTime(rMsg.getCreateTime());
		msgs.setFromUserName(rMsg.getToUserName());
		msgs.setToUserName(rMsg.getFromUserName());
		return msgs.convert2xml();
	}
	/**
	 * 得到默认回复信息
	 * */
	private Wxsendmsg defaultmsg(String siteid)throws Exception{
		return wxsendmsgService.findByKeyWord(WeiXinConstant.WEIXIN_MSGTYPE_DEFAULT, siteid);
	}
	//根据接收的实体返回回复信息
	private BaseMsg sendMsg(Wxsendmsg smsg, BaseMsg rmsg)throws Exception{
		String msgtype = smsg.getMsgtype();
		//图文回复
		if(WeiXinConstant.WEIXIN_MSGTYPE_NEWS.equals(msgtype)){
			ImgTextSMsg img_txt_msg = new ImgTextSMsg();
			img_txt_msg.setMsgType(WeiXinConstant.WEIXIN_MSGTYPE_NEWS);
			
			WxsendmsgDto dto = new WxsendmsgDto();
			dto.setPid(smsg.getId());
			dto.setRtype(WeiXinConstant.WEIXIN_MSGTYPE_NEWS);
			List<Map<String, Object>> childs = wxsendmsgService.findNewsMapByDto(dto);
			if(CollectionUtils.isEmpty(childs))
				return img_txt_msg;
			for(Map<String, Object> child : childs){
				ImgTextItem img_txt = img_txt_msg.initItem();
				img_txt.setDescription(NimsenUtil.obj2String(child.get("rtext")));
				img_txt.setPicUrl(NimsenUtil.obj2String(child.get("filename")));
				img_txt.setTitle(NimsenUtil.obj2String(child.get("title")));
				img_txt.setUrl(NimsenUtil.obj2String(child.get("url"))+"?openid="+rmsg.getFromUserName());
				img_txt_msg.add(img_txt);
			}
			
			return img_txt_msg;
		//默认回复
		}else if(WeiXinConstant.WEIXIN_MSGTYPE_DEFAULT.equals(msgtype)){
			Wxsendmsg tarmsg = wxsendmsgService.findByid(smsg.getTargetid());
			return sendMsg(tarmsg, rmsg);
		}else{
			TextSMsg txt_msg = new TextSMsg();
			txt_msg.setContent(smsg.getRtext());
			txt_msg.setMsgType(WeiXinConstant.WEIXIN_MSGTYPE_TEXT);
			return txt_msg;
		}
	}
}
